<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="view ? '查看不良记录' : (isEdit ? '修改不良记录' : '新增不良记录')"
    width="800px"
    :visible.sync="visible"
  >
    <el-form :model="form" ref="form" :disabled="view" :rules="rules" label-width="110px">
      <el-form-item v-show="false" label="不良Id">
        <a-input :disabled="true" v-model="form.badId" />
      </el-form-item>
      <el-form-item label="不良类型" prop="badType">
        <el-select style="width: 100%" placeholder="请选择" v-model="form.badType" clearable>
          <el-option
            v-for="item in badTypeArr"
            :key="item.value"
            :value="item.value"
            :label="item.title"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierCode">
        <access-supplier
          style="width: 100%"
          :selectValue="form.supplierCode"
          v-model="form.supplierCode"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item label="关系人">
        <el-select
          value-key="linkmanId"
          multiple
          mode="tags"
          v-model="form.linkmanList"
          style="width: 100%"
          @change="handleChange"
        >
          <el-option
            v-for="item in allLink"
            :key="item.linkmanId"
            :value="item"
            :label="item.linkmanName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发生日期" prop="badDate">
        <el-date-picker
          type="date"
          placeholder="请选择发生日期"
          v-model="form.badDate"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="事件描述">
        <el-input
          type="textarea"
          placeholder="请输入"
          v-model="form.badContent"
          maxlength="1300"
          show-word-limit
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>
      <el-form-item label="新增附件">
        <el-upload
          action="https://jsonplaceholder.typicode.com/posts/"
          :multiple="true"
          :file-list="fileList"
          :on-remove="handleRemove"
          :on-preview="handlePreview"
          :on-change="info => uploadChange(info)"
          :http-request="customRequest"
        >
          <el-button>
            <i class="el-icon-upload" />点击选择文件上传
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" v-if="!view">
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        @click="handleOk"
        :loading="confirmLoading"
      >{{ isEdit ? '修改' : '新增' }}</el-button>
    </div>
    <preview-modal ref="previewModal" />
  </el-dialog>
</template>

<script>
import { updateBad, insertBad, allLinkMan, saveOnlyUploads } from '@/api/supplier'
// import SupplierSelect from '../components/SupplierSelect'
import AccessSupplier from '../components/AccessSupplier'
import { openNotification, getDicData, formatY } from '@/utils/util'
import pick from 'lodash.pick'
import PreviewModal from '@/components/PreviewModal'

export default {
  components: {
    PreviewModal,
    AccessSupplier
  },
  data() {
    return {
      visible: false,
      isEdit: false,
      form: {
        badId: null,
        badType: null,
        supplierCode: null,
        linkmanList: null,
        badDate: null,
        badContent: null,
        uploadId: null
      },
      rules: {
        badType: [{ required: true, message: '请选择不良类型', trigger: 'blur' }],
        supplierCode: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
        badDate: [{ required: true, message: '请选择发生日期', trigger: 'blur' }]
      },
      confirmLoading: false,
      mdl: {},
      linkmanList: [],
      linkInfoList: [],
      allLink: [],
      badTypeArr: [],
      selectValue: '',
      fileList: [],
      view: false // 查看
    }
  },
  async mounted() {
    // 联系人列表获取
    this.badTypeArr = getDicData('002', '002006')
  },
  methods: {
    // 预览图片
    handlePreview(file) {
      let arr = []
      this.fileList.map(v => {
        arr.push(v.savePath)
      })
      this.$refs.previewModal.show(arr)
      // console.log('tableData', this.itemArr[index].tableData, ind, one)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.fileList = [...fileList]
    },
    async getLinkMan(supplierCode) {
      const res = await allLinkMan({ supplierCode })
      console.log('link man res', res)

      if (res && res.data.length > 0) {
        const { data } = res
        this.allLink = data
      }
    },
    handleChange(value) {
      this.linkmanList = value
    },
    edit(bool, record, view = false) {
      console.log('edit', bool, record)
      this.view = view
      this.visible = true
      this.isEdit = bool
      this.form = pick(record, 'badId', 'badType', 'supplierCode', 'badDate', 'badContent')
      if (bool) {
        this.getLinkMan(record.supplierCode)
        this.form.linkmanList = JSON.parse(record.linkmanList)
        if (record.savePath) {
          // 有文件上传，回显文件
          this.fileList = [...record.savePath]
          this.fileList.map((v, i) => {
            v.uid = i
            v.name = '附件' + Number(i + 1)
            v.url = v.savePath
          })
        }
        console.log('fileList', this.fileList)
      }
      console.log('form', this.form)

      // this.$nextTick(() => {})
    },
    handleOk(e) {
      e.stopPropagation()
      this.confirmLoading = true
      this.$refs.form.validate(async valid => {
        if (valid) {
          let res = ''
          let mes = ''
          this.form.linkmanList.map(values => {
            // 清空其他值为null的属性
            Object.keys(values).map(v => {
              if (!values[v]) {
                delete values[v]
              }
              return true
            })
          })
          this.form.linkmanList = JSON.stringify(this.form.linkmanList)
          if (this.fileList.length > 0) {
            let arr = []
            this.fileList.map(v => {
              arr.push(v.uploadId)
            })
            this.$set(this.form, 'uploadId', arr.join(','))
          }
          console.log('form', this.form)

          if (this.isEdit) {
            res = await updateBad(this.form)
            mes = '修改操作成功'
          } else {
            res = await insertBad(this.form)
            mes = '新增操作成功'
          }
          this.confirmLoading = false
          openNotification('success', mes)
          this.visible = false
          this.fileList = []
          this.$emit('refresh')
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleSelect(value) {
      this.getLinkMan(value)
      this.$set(this.form, 'supplierCode', value)
      this.$set(this.form, 'linkmanList', null)
    },
    uploadChange(info) {
      console.log('info', info)
      // this.fileList = info.fileList
    },
    customRequest(info) {
      // const _this = this
      console.log('customRequest', info)
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          this.fileList.push(data)
          // this.fileList[this.fileList.length - 1].status = 'done'
          this.fileList[this.fileList.length - 1].url = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].savePath = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].name = data.uploadTitle

          console.log('fileList', this.fileList)

          // this.fileList.map(v => {
          //   v.status = 'done'
          //   v.uploadId = data.uploadId
          //   v.url = data.fileUrl + data.fileName
          // })
          // this.fileList = [...this.fileList]
        }
      })
    }
  }
}
</script>
